package com.graduation.cdm.funactivity.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.graduation.cdm.funactivity.MyApplication;
import com.graduation.cdm.funactivity.R;
import com.graduation.cdm.funactivity.bean.ActivityBean;
import com.graduation.cdm.funactivity.bean.Evaluate;
import com.graduation.cdm.funactivity.bean.EvaluateBean;
import com.graduation.cdm.funactivity.bean.User;
import com.graduation.cdm.funactivity.bean.UserBean;
import com.graduation.cdm.funactivity.util.CommonAdapter;
import com.graduation.cdm.funactivity.util.ViewHolder;
import com.graduation.cdm.funactivity.util.ownview.ListViewForScrollView;
import com.graduation.cdm.funactivity.util.ownview.ListenerForScrolView;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.graduation.cdm.funactivity.util.DateUtils.longToDatestring;
import static com.graduation.cdm.funactivity.util.GlobalConstant.preUrl;
import static com.graduation.cdm.funactivity.util.GlobalConstant.userId;
import static com.graduation.cdm.funactivity.util.getUtils.getUser;
import static com.graduation.cdm.funactivity.util.xUtilsImageUtils.displayHead;
import static com.graduation.cdm.funactivity.util.xUtilsImageUtils.displayXianXi;

public class OperateJoinActivity extends AppCompatActivity implements View.OnClickListener {

    private ListenerForScrolView scrollview;
    private RelativeLayout bottom;
    private RelativeLayout bottom1;
    private TextView tvLable;
    private TextView tvTheme;
    private TextView tvTimeDetail;
    private TextView tvNumDetail;
    private TextView tvGather;
    private TextView tvAddress;
    private ImageView activity_fm;
    private TextView tvDetail;
    private TextView tvCareDetail;
    private ImageView head;
    private TextView userName;
    private TextView userPhone;

    private int mLastScrollY;
    private int mScrollThreshold = 3;
    Boolean seeFlag=false;

    String evaluateContent = null;
    Integer activityId;
    ActivityBean.Activity activity;
    private TextView tvCreatetime;
    private GridView gvJoiner;

    CommonAdapter<User> userCommonAdapter;
    CommonAdapter<Evaluate> evaluateCommonAdapter;
    private ListViewForScrollView lvEva;
    private TextView joinNum;
    private ImageView evaMore;
    private ImageView ivBack;
    private TextView tvEvaluate;
    private TextView tvEvaluatedetails;
    private TextView tcAct;

    Set<String> ev = new HashSet<String>();
    private EditText edtEva;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_operate_join);

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        userId = sharedPreferences.getInt("userId",0);

        initView();
        initData();
        getData();
        initEvent();

    }

    private void initView(){
        scrollview = ((ListenerForScrolView) findViewById(R.id.scrollview));
        bottom = ((RelativeLayout) findViewById(R.id.bottom));
        bottom1 = ((RelativeLayout) findViewById(R.id.bottom1));
        tvLable = ((TextView) findViewById(R.id.tv_lable));
        tvTheme = ((TextView) findViewById(R.id.tv_theme));
        tvCreatetime = ((TextView) findViewById(R.id.tv_creattime));
        tvTimeDetail = ((TextView) findViewById(R.id.tv_time_detail));
        tvNumDetail = ((TextView) findViewById(R.id.tv_num_detail));
        tvGather = ((TextView) findViewById(R.id.tv_gather));
        tvAddress = ((TextView) findViewById(R.id.tv_address));
        activity_fm = ((ImageView) findViewById(R.id.act_fm));
        tvDetail = ((TextView) findViewById(R.id.tv_detail));
        tvCareDetail = ((TextView) findViewById(R.id.tv_care_detail));
        head = ((ImageView) findViewById(R.id.head));
        userName = ((TextView) findViewById(R.id.user_name));
        userPhone = ((TextView) findViewById(R.id.user_phone));

        gvJoiner = ((GridView) findViewById(R.id.gv_joiner));
        lvEva = ((ListViewForScrollView) findViewById(R.id.lv_eva));

        joinNum = ((TextView) findViewById(R.id.join_num));
        evaMore = ((ImageView) findViewById(R.id.eva_more));
        ivBack = ((ImageView) findViewById(R.id.iv_back));
        tvEvaluate = ((TextView) findViewById(R.id.tv_evaluate));
        tvEvaluatedetails = ((TextView) findViewById(R.id.tv_evaluate_detail));
        tcAct = ((TextView) findViewById(R.id.tc_act));
        edtEva = ((EditText) findViewById(R.id.edt_eva));
        joinNum.setOnClickListener(this);
        evaMore.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        tvEvaluate.setOnClickListener(this);
        tvEvaluatedetails.setOnClickListener(this);
        tcAct.setOnClickListener(this);

        scrollview.smoothScrollTo(0, 0);
        scrollview.setOnScrollChangedListener(new ListenerForScrolView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
                boolean isSignificantDelta = Math.abs(t - mLastScrollY) > mScrollThreshold;
                if (isSignificantDelta) {
                    if (t > mLastScrollY) {
                        bottom.setVisibility(View.GONE);
                        bottom1.setVisibility(View.GONE);
                    } else {
                        bottom.setVisibility(View.VISIBLE);
                        if (seeFlag) {
                            bottom1.setVisibility(View.VISIBLE);
                        }
                    }
                }
                mLastScrollY = t;
            }
        });
    }

    private void initData(){
        Intent intent = getIntent();
        activity = (ActivityBean.Activity) intent.getSerializableExtra("activityInfo");
        System.out.println("initData+===" + activity);
        if (activity != null) {
            activityId=activity.activityId;
            tvLable.setText(activity.activityLabel);
            tvTheme.setText(activity.activityTheme);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
            tvCreatetime.setText(sdf.format(activity.activityCreattime));
            tvTimeDetail.setText(sdf.format(activity.activityBegintime) + "——" + sdf.format(activity.activityEndtime));
            String maxPeople = String.valueOf(activity.activityMaxPeopleNumber);
            tvNumDetail.setText(maxPeople.equals("0") ? "不限" : maxPeople);
            tvGather.setText(activity.activityProvince+activity.activityCity);
            tvAddress.setText(activity.activityAddress);

            displayXianXi(activity_fm,preUrl+activity.activityImgurl);

            tvDetail.setText(activity.activityDesc);
            tvCareDetail.setText(activity.activityCare);

            getUser(activity,head,userName,userPhone);

            getJoiner(activity);
        }
    }

    public void initEvent() {
        SharedPreferences share = getSharedPreferences("evaluate", Context.MODE_PRIVATE);
        //ev.add("false,null");
        Set<String> resultSet = share.getStringSet(activity.activityId + "", ev);
        if (!resultSet.toString().equals("[]")) {
            System.out.println(activity.activityId + "===" + resultSet);
            String[] results = resultSet.toString().split(",", 2);
            System.out.println(results[0] + "+++" + results[1]);
            //String id=String.valueOf(activity.getActivityId());
            if (("[" + activity.activityId).equals(results[0])) {
                System.out.println("asdasda");
                String result = results[1];
                if (result.charAt(result.length() - 1) == ']') {
                    edtEva.setText(results[1].substring(0, results[1].length() - 1));
                } else {
                    edtEva.setText(result);
                }
                tvEvaluate.setText("继续评论");
            }
        }

    }

    public void getJoiner(ActivityBean.Activity activty){
        String url = preUrl + "user/getJoiner";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("=userList="+s.trim());
                Gson gson = new Gson();
                UserBean userBean = gson.fromJson(s,UserBean.class);
                List<User> joinList = userBean.userList;
                setJoiner(joinList);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("==="+volleyError.toString());
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map=new HashMap<>();
                map.put("activityId",activity.activityId+"");
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

    private void setJoiner(List<User> joinList){
        userCommonAdapter=new CommonAdapter<User>(getApplicationContext(),joinList,R.layout.joiner_gv_item) {
            @Override
            public void convert(ViewHolder viewHolder, User user, int position)  {
                ImageView head=viewHolder.getViewById(R.id.user_head);
                displayHead(head,preUrl+user.getImageUrl());
            }
        };
        gvJoiner.setAdapter(userCommonAdapter);
    }

    public void getData() {
        String url=preUrl+"evaluate/getEvaluate";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("+eva+"+s.trim());
                Gson gson = new Gson();
                EvaluateBean evaluateBean = gson.fromJson(s,EvaluateBean.class);
                List<Evaluate> evaluates = evaluateBean.evaluateList;
                setEvaluate(evaluates);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map=new HashMap<>();
                map.put("pageNow",1+"");
                map.put("pageSize",4+"");
                map.put("activityId",activity.activityId+"");
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

    private void setEvaluate(List<Evaluate> evaluates){
        evaluateCommonAdapter=new CommonAdapter<Evaluate>(getApplicationContext(),evaluates,R.layout.evaluate_item) {
            @Override
            public void convert(ViewHolder viewHolder, Evaluate evaluate, int position) {
                TextView tvContent=viewHolder.getViewById(R.id.tv_content);
                TextView tvTime = viewHolder.getViewById(R.id.tv_time);
                TextView tvName = viewHolder.getViewById(R.id.tv_name);
                ImageView ivHead = viewHolder.getViewById(R.id.iv_head);

                tvContent.setText(evaluate.getEvaluateContent());
                tvTime.setText(longToDatestring(evaluate.getEvaluateTime()));

                getUser(evaluate.getUserId(),ivHead,tvName);
            }
        };
        lvEva.setAdapter(evaluateCommonAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.eva_more:
                break;
            case R.id.join_num:
                break;
            case R.id.tv_evaluate:
                bottom1.setVisibility(View.VISIBLE);
                seeFlag=true;
                break;
            case R.id.tv_evaluate_detail:
                System.out.println("btn");
                ev.clear();
                insertEva();
                ev.add(activity.activityId + "," + edtEva.getText().toString());
                SharedPreferences sharedPreferences = getSharedPreferences("evaluate", Context.MODE_PRIVATE); //私有数据
                SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                //editor.putString("evaluateContent", evaluateContent);
                editor.putStringSet(activity.activityId + "", ev);
                //editor.putInt("activityId", activityId);
                editor.commit();//提交修改
                Toast.makeText(getApplicationContext(),"发表成功！",Toast.LENGTH_SHORT).show();
                bottom1.setVisibility(View.GONE);
                seeFlag=false;
                break;
            case R.id.tc_act:
                deleteJoin();
                Intent intent1=new Intent();
                setResult(200,intent1);
                finish();
                break;
        }
    }

    public void insertEva(){
        evaluateContent = edtEva.getText().toString();
        String url = preUrl+"evaluate/addEvaluate";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("insert==="+s.trim());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map=new HashMap<>();
                map.put("userId",userId+"");
                map.put("evaluateContent",evaluateContent);
                map.put("activityId",activity.activityId+"");
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

    public void deleteJoin(){
        String url = preUrl+"activity/deleteJoiner";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("deleete=="+s.trim());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("activityId",activity.activityId+"");
                map.put("userId",userId+"");
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

}
